package top.jfunc.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.context.ServletContextAware;

public class SpringContextUtil implements ApplicationContextAware, ServletContextAware {

	private static ApplicationContext context;
	private static javax.servlet.ServletContext servletContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.context = applicationContext;
    }

	/**
	 * 在javax.servlet环境下自动调用该方法
	 */
	@Override
	public void setServletContext(javax.servlet.ServletContext servletContext) {
		SpringContextUtil.servletContext = servletContext;
	}

	/**
	 * 根据名称获取bean
	 */
	public static Object getBean(String beanName) {
		return context.getBean(beanName);
	}

	/**
	 * 根据bean名称获取指定类型bean
	 *
	 * @param beanName bean名称
	 * @param clazz 返回的bean类型,若类型不匹配,将抛出异常
	 */
	public static <T> T getBean(String beanName, Class<T> clazz) {
		return context.getBean(beanName, clazz);
	}

	public static <T> T getBean(Class<T> clazz) {
		return context.getBean(clazz);
	}
	public static String getApplicationName() {
		return context.getEnvironment().getProperty("spring.application.name");
	}

	public static String getActiveProfile() {
		return context.getEnvironment().getProperty("spring.profiles.active");
	}
	public static String[] getActiveProfiles() {
		return context.getEnvironment().getActiveProfiles();
	}
	public static String getRequiredProperty(String key){
		return context.getEnvironment().getRequiredProperty(key);
	}

	public static String getProperty(String key){
		return context.getEnvironment().getProperty(key);
	}

	/**
	 * 任意时空获取ApplicationContext
	 */
	public static ApplicationContext getContext() {
		return context;
	}
	/**
	 * 任意时空获取javax.servlet.ServletContext
	 */
	public static javax.servlet.ServletContext getServletContext() {
		return servletContext;
	}


	public static void registerMyself(ConfigurableApplicationContext applicationContext){
		registerMyself((DefaultListableBeanFactory) applicationContext.getBeanFactory());
	}
	public static void registerMyself(BeanDefinitionRegistry registry){
		AbstractBeanDefinition beanDef = new GenericBeanDefinition();
		beanDef.setBeanClass(SpringContextUtil.class);
		registry.registerBeanDefinition(SpringContextUtil.class.getSimpleName(), beanDef);
	}
}
